import { reactive } from "vue";
import type { FormRules } from "element-plus";

/** 自定义表单规则校验 */
export const formRules = reactive(<FormRules>{
  account_id: [{ required: true, message: "请选择广告账号", trigger: "change" }],
  amount: [
    { required: true, message: "充值金额为必填项", trigger: "blur" },
    { 
      pattern: /^(0|[1-9]\d*)(\.\d{1,2})?$/, 
      message: "金额格式不正确，最多保留两位小数", 
      trigger: "blur" 
    },
    {
      validator: (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error("充值金额必须大于0"));
        } else if (value > 999999999.99) {
          callback(new Error("充值金额不能超过999999999.99"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
});

/** 处理表单规则校验 */
export const processFormRules = reactive(<FormRules>{
  state: [{ required: true, message: "请选择处理状态", trigger: "change" }],
  feedback_content: [
    { max: 255, message: "反馈内容不能超过255个字符", trigger: "blur" }
  ]
});

/** 批量申请表单规则校验 */
export const batchFormRules = reactive(<FormRules>{
  accounts: [
    { required: true, message: "请至少添加一个充值申请", trigger: "change" },
    {
      validator: (rule, value, callback) => {
        if (!Array.isArray(value) || value.length === 0) {
          callback(new Error("请至少添加一个充值申请"));
        } else {
          // 验证每个申请项
          for (let i = 0; i < value.length; i++) {
            const account = value[i];
            if (!account.account_id) {
              callback(new Error(`第${i + 1}行：请选择广告账号`));
              return;
            }
            if (!account.amount || account.amount <= 0) {
              callback(new Error(`第${i + 1}行：请输入有效的充值金额`));
              return;
            }
            if (account.amount > 999999999.99) {
              callback(new Error(`第${i + 1}行：充值金额不能超过999999999.99`));
              return;
            }
          }
          
          // 检查是否有重复的账号
          const accountIds = value.map(item => item.account_id).filter(id => id);
          const uniqueIds = [...new Set(accountIds)];
          if (accountIds.length !== uniqueIds.length) {
            callback(new Error("存在重复的广告账号，请检查"));
            return;
          }
          
          callback();
        }
      },
      trigger: "change"
    }
  ]
});
